package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.RecommendationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: xiaomi
 * @date: 2021/10/9
 * @description: 商品推荐
 * key的 表示为：COMMODITY_RECOMMENDATION_KEY+ source
 */
@Service
@Slf4j
public class CommodityRecommendationServiceImpl implements RecommendationService {

    final String COMMODITY_RECOMMENDATION_KEY = "commodity::recommendation";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean addPath(String source, String dest) {
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        String key = getKey(source);
        Double aDouble = opsForZSet.incrementScore(key, dest, 1);
        log.info("addPath res:{}", aDouble);
        return aDouble > 0;
    }

    @Override
    public List<String> recommendationTop10(String source) {
        ZSetOperations<String, String> opsForZSet = stringRedisTemplate.opsForZSet();
        String key = getKey(source);
        Set<ZSetOperations.TypedTuple<String>> typedTuples = opsForZSet.reverseRangeWithScores(key, 0, 9);
        List<String> list = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            list.add(typedTuple.getValue() + ":" + typedTuple.getScore());
        }
        log.info("{} top 10:{}", source, list);
        return list;
    }

    String getKey(String source) {
        String key = COMMODITY_RECOMMENDATION_KEY + "::" + source;
        return key;
    }
}
